<!-- 
    time：20024-4-20
    name：meidusa 
    role：拖拽排序
 -->

<template>
    <div class="drag-sort-box">
        <div class="drag-sort-box-list" ref="listdom" @dragstart="dragstartFn" @dragenter="ondragenterFn" @dragover="dragoverFn"
            @dragend="dragendFn">
            <div :draggable="true" class="drag-sort-box-list-item" v-for="(item, index) in arr" :key="index">{{ item }}</div>
        </div>
    </div>
</template>

<script setup lang='ts'>
import { ref } from 'vue';
let arr = ref([1, 2, 3, 4, 5])
let listdom = ref()
let sourceNode = ref(); // 记录节点

/**
 * 拖拽开始
 * @param e 事件
 */
const dragstartFn = (e: any) => {
    setTimeout(() => {
        e.target.classList.add('moving')
    }, 0)
    sourceNode.value = e.target
}

/**
 * 拖拽到目标元素上
 * 阻止默认行为
 * @param e  事件
 */
const dragoverFn = (e: any) => {
    e.preventDefault(); // 阻止浏览器默认行为
}

/**
 * 拖拽进入目标元素
 * @param e  事件
 */
const ondragenterFn = (e: any) => {
    e.preventDefault(); // 阻止浏览器默认行为

    if (e.target == listdom.value || e.target == sourceNode.value) return

    const children = [...listdom.value.children]
    const sourceIndex = children.indexOf(sourceNode.value)
    const targetIndex = children.indexOf(e.target)
    if (sourceIndex < targetIndex) {
        listdom.value.insertBefore(sourceNode.value, e.target.nextElementSibling);
    } else {
        listdom.value.insertBefore(sourceNode.value, e.target);
    }
}

/**
 * 拖拽之后
 */
const dragendFn = () => {
    sourceNode.value.classList.remove('moving')
}

</script>

<style lang="scss" scoped>
.drag-sort-box-list {
    width: 100%;
    margin-top: 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .moving{
        opacity: 1 !important;
    }

    .drag-sort-box-list-item {
        width: 80%;
        height: 50px;
        line-height: 50px;
        border-radius: 5px;
        margin: 10px;
        cursor: move;
        user-select: none;

        &:nth-child(1) {
            background-color: #f50808;
        }

        &:nth-child(2) {
            background-color: #f5d208 !important;
        }

        &:nth-child(3) {
            background-color: #08f5ce;
        }

        &:nth-child(4) {
            background-color: #0883f5;
        }

        &:nth-child(5) {
            background-color: #3408f5;
        }
    }

    .drag-sort-box-list-item.moving {
        background: transparent;
        color: transparent;
        border: 1px solid #ccc;
    }
}
</style>